package com.ai.dmc.index.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ai.dmc.cache.redis.client.service.IRedisClientService;
import com.ai.dmc.index.common.bean.StaffSessBean;
import com.ai.dmc.index.web.util.Constants;
import com.ai.dmc.index.web.util.PropertiesUtil;
import com.ai.frame.util.JsonUtil;


/**
 * 登录过滤
 * 
 * @author zhangyang6
 */
public class SessionFilter extends OncePerRequestFilter {
	IRedisClientService redisClientService;
    // 登录页面
    private String LoginPage = PropertiesUtil.getString("LOGIN_HTML");

    @SuppressWarnings("unchecked")
	@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    	//Filter比Bean先加载，无法通过注入获取，通过系统配置获取
    	WebApplicationContext web = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    	
    	redisClientService = (IRedisClientService)web.getBean("redisClientService");
        // 不过滤的uri
    	String[] notFilter = new String[] {"/lib", "/css","/images", "/logout", "/druid","/ssoAuth" ,"/login","/front/sh/"};
    	String[] notFilterEnd = new String[] {".js"};

    	// 请求的uri
        String url = request.getRequestURL().toString();
        //Token
        String token = request.getParameter("token");
        
       Map<Object,Object> paramMap = request.getParameterMap();
        // 是否过滤
        boolean doFilter = true;
        for (String s : notFilter) {
            if (url.indexOf(s) != -1) {
                // 如果uri中包含不过滤的uri，则不进行过滤
                doFilter = false;
                break;
            }
        }
        if (doFilter) {
			for (String s : notFilterEnd) {
				if (url.endsWith(s)) {
	                // 如果uri中包含不过滤的uri，则不进行过滤
	                doFilter = false;
	                break;
	            }
			}
		}
        if (doFilter) {
            // 执行过滤
            // 从session中获取登录者实体
        	StaffSessBean user = (StaffSessBean) request.getSession().getAttribute(Constants.SESSION_USER);
            // 设置request和response的字符集，防止乱码
            response.setContentType("text/html;charset=UTF-8");
            //如果未登陆，则跳转到登陆页面
            if (null == user) {
            	response.sendRedirect(LoginPage);
            	return;
            } else {
            	filterChain.doFilter(request, response);
                return;
            }
        } else {
            // 如果不执行过滤，则继续
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 判断是否为Ajax请求 <功能详细描述>
     * 
     * @param request
     * @return 是true, 否false
     * @see [类、类#方法、类#成员]
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header))
            return true;
        else
            return false;
    }
    /**
     * 
     * 验证Token是否存在
     * @param tokenValue
     * @return
     * @throws IOException
     */
    private JSONObject checkTokenInfo(String tokenValue) throws IOException {
        String checkUrl = PropertiesUtil.getString("com.zyzx.aqs.tokenCheckUrl")+tokenValue;
        HttpClient httpclient = new HttpClient();
        GetMethod httpget = new GetMethod(checkUrl);
        try {
            httpclient.executeMethod(httpget);
            String result = httpget.getResponseBodyAsString();
            JSONObject json = JSONObject.fromObject(result);
            return json;
        } finally {
            httpget.releaseConnection();
        }
    }
    
    private String getParamUrl(Map<Object,Object> paramMap,String sign) throws UnsupportedEncodingException{
        String paramUrl ="";
        if(paramMap.isEmpty()){
            return "";
        }
        for(Iterator<Entry<Object, Object>> iter = paramMap.entrySet().iterator();iter.hasNext();){ 
                
                Map.Entry element = (Map.Entry)iter.next(); 
                Object strKey = element.getKey(); 
                String[] value=(String[])element.getValue(); 
                
                String keyValue ="&"+strKey+"=";
                String valueStr="";
                
                for(int i=0;i <value.length;i++){ 
                    valueStr += value[i] +",";
                    keyValue += valueStr;
                } 
                
                paramUrl += keyValue.substring(0, keyValue.length()-1);
        } 
        paramUrl = sign+paramUrl.substring(1);
        return paramUrl;
    }
    
}
